import {Text, View} from "@tarojs/components";
import {useRef, useCallback, useEffect, useState} from "react"; // Added useCallback
import DateUtils, {DateTab} from "@/utils/date_utils";
import Utils from "@/utils/common"; // Assuming Utils.classNames or similar might be useful
import RouthPath from "@/common/RouthPath";
import {MachineModel} from "@/common/apis/model";
import {orderTimeApi} from "@/common/apis/home_datasource";
import {Order_times_listProps} from "@/pages/order/order_times_list";
import './order_statistics_page.less';

const RECENT_DAYS_COUNT = 30;

definePageConfig({
  navigationBarTitleText: '预约情况'
});

export default function OrderStatisticsPage() { // Renamed for convention (PascalCase)
                                                // Initialize dateTabs once
  const dateTabs = useRef(DateUtils.getRecentDateTabs(DateUtils.getTodayBefore(10), RECENT_DAYS_COUNT));
  const machineModel = useRef<MachineModel>();

  const [timeS, setTimeS] = useState<String[]>()

  const handleDateTabClick = useCallback((item: DateTab) => {
    // It's generally better to use Taro.navigateTo directly for clarity
    if (item.title) {
      const data: Order_times_listProps = {
        item: item,
        model: machineModel.current!
      }
      Utils.navigateTo({
        url: Utils.getUrlWithObject(RouthPath.orderTimeList, data),
      });
    }
  }, []); // No dependencies, so it's created once


  useEffect(() => {
    const i = Utils.getParamsByRouter(Utils.getI())
    if (i && i.data) {
      machineModel.current = Utils.getObjectWithUrl<MachineModel>(i.data)
      orderTimeApi(machineModel.current?.id).then((res) => {
        if (res) {
          setTimeS(res)
        }
      })
    }
  }, []);


  const renderItem = useCallback((item) => {
    const num = DateUtils.countDateTimeEntriesByDate(timeS, item.id)
    const itemClasses = Utils.classNames( // Assuming you have a classnames utility
      'grid-item',
      {'grid-item--highlighted': num > 0}
    );
    return (
      <View
        key={item.id} // Use a more stable key if available (like an ID or full date string)
        className={itemClasses}
        onClick={() => handleDateTabClick(item)}
      >
        {/* Removed redundant inner View, parent flex properties should suffice */}
        <Text style={{fontSize: '14px', color: 'black'}}>{item.title}</Text>
        <Text style={{
          color: num > 0 ? 'green' : 'black',
          fontSize: '14px'
        }}>已预约：{DateUtils.countDateTimeEntriesByDate(timeS, item.id)}</Text> {/* This is static, consider making it dynamic */}
      </View>
    );
  }, [handleDateTabClick, timeS]);


  return (
    <View className='order-statistics-container'>
      <View className='gridLayout100'>
        {dateTabs.current.map((item, index) => {
          // Conditionally apply a class for styling
          return renderItem(item);
        })}
      </View>
    </View>
  );
}
